package com.l024.loanthief.views.chat;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.alibaba.fastjson.JSON;
import com.l024.loanthief.R;
import com.l024.loanthief.adapter.CommonAdapter;
import com.l024.loanthief.adapter.CommonViewHolder;
import com.l024.loanthief.base.activity.BaseActivity;
import com.l024.loanthief.constant.APPConstant;
import com.l024.loanthief.databinding.ActivityChatBinding;
import com.l024.loanthief.entity.ChatMessageEntity;
import com.l024.loanthief.entity.UserEntity;
import com.l024.loanthief.eventbus.ChatMessageEvent;
import com.l024.loanthief.help.AppHelp;
import com.l024.loanthief.help.GlideHelp;
import com.l024.loanthief.utils.CameraUtil;
import com.l024.loanthief.utils.FileUtil;
import com.l024.loanthief.utils.ImageUtil;
import com.l024.loanthief.utils.Logutils;
import com.wildma.pictureselector.PictureBean;
import com.wildma.pictureselector.PictureSelector;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.annotations.NonNull;
import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.core.ObservableEmitter;
import io.reactivex.rxjava3.core.ObservableOnSubscribe;
import io.reactivex.rxjava3.functions.Consumer;
import io.reactivex.rxjava3.schedulers.Schedulers;
import me.rosuh.filepicker.config.FilePickerManager;

public class ChatActivity extends BaseActivity implements View.OnClickListener {


    private CommonAdapter<ChatMessageEntity> chatMessageAdapter;
    private List<ChatMessageEntity> chatMessages = new ArrayList<>();;

    private ActivityChatBinding binding;

    private UserEntity userEntity;
    private  Animation mShowAction;
    private  Animation mCloseAction;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this,R.layout.activity_chat);
        EventBus.getDefault().register(this);
        addStatusColor(this, getResources().getColor(R.color.themeColor));
        init();
        initData();
    }


    private void initData() {
        Intent intent = getIntent();
        if(intent!=null){
            String deviceInfo = intent.getStringExtra("deviceInfo");
            if(!TextUtils.isEmpty(deviceInfo)){
                userEntity = JSON.parseObject(deviceInfo, UserEntity.class);
                if(deviceInfo!=null){
                    EventBus.getDefault().postSticky(new ChatMessageEvent(APPConstant.START_CHAT_SERVICE,"",userEntity.getIp()));
                    binding.tvTitle.setText(String.format("%s(%s)", userEntity.getName(), userEntity.getIp()));
                }
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN,sticky = true)
    public void message(ChatMessageEvent event) {
        if(event!=null){
            switch (event.getCode()){
                case APPConstant.RECEIVE_TEXT_CODE:{
                    //文本消息
                    addTextMsg(event.getData().toString(),0);
                    break;
                }
                case APPConstant.RECEIVE_IMG_CODE:{
                    //图片消息
                    addImageMsg(event.getData().toString(),0);
                    break;
                }
                case APPConstant.RECEIVE_FILE_CODE:{
                    //文件消息
                    String filePath = event.getData()+"";
                    if(!TextUtils.isEmpty(filePath)){
                        File file = new File(filePath);
                        if(file.exists()){
                            addFileMsg(file.getName(),0);
                        }
                    }
                    break;
                }
                case APPConstant.SEND_ERROR:{
                    Toast.makeText(this, "发送失败，请重新发送", Toast.LENGTH_SHORT).show();
                    break;
                }
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().removeAllStickyEvents();
        EventBus.getDefault().unregister(this);
        if(mShowAction!=null){
            mShowAction.reset();
            mShowAction.cancel();
        }
        if(mCloseAction!=null){
            mCloseAction.reset();
            mCloseAction.cancel();
        }
    }

    private void init() {
        binding.sendBtn.setOnClickListener(this);
        binding.ivMore.setOnClickListener(this);
        binding.ivChatCamera.setOnClickListener(this);
        binding.ivChatImages.setOnClickListener(this);
        binding.ivChatFile.setOnClickListener(this);
        chatMessageAdapter = new CommonAdapter<ChatMessageEntity>(chatMessages, new CommonAdapter.OnMoreBindDataListener<ChatMessageEntity>() {
            @Override
            public int getItemType(int position) {
                return chatMessages.get(position).getPosition();
            }

            @Override
            public void onBindViewHolder(ChatMessageEntity model, CommonViewHolder viewHolder, int type, int position) {
                ImageView img = (ImageView)viewHolder.getView(R.id.iv_avator);
                img.setImageResource(userEntity.getIcon());
                //设置文字图片
                if(APPConstant.RECEIVE_TEXT_CODE.equals(model.getType())){
                    viewHolder.getView(R.id.tv_msg).setVisibility(View.VISIBLE);
                    viewHolder.getView(R.id.iv_img).setVisibility(View.GONE);
                    viewHolder.setText(R.id.tv_msg,chatMessages.get(position).getMsg());
                }else if(APPConstant.RECEIVE_IMG_CODE.equals(model.getType())){
                    viewHolder.getView(R.id.tv_msg).setVisibility(View.GONE);
                    ImageView iv = viewHolder.getView(R.id.iv_img);
                    iv.setVisibility(View.VISIBLE);
                    GlideHelp.getInstance().setImg(ChatActivity.this,model.getMsg(),iv);
                }else if(APPConstant.RECEIVE_FILE_CODE.equals(model.getType())){
                    //文件
                    viewHolder.getView(R.id.tv_msg).setVisibility(View.GONE);
                    ImageView iv = viewHolder.getView(R.id.iv_img);
                    iv.setVisibility(View.VISIBLE);
                    GlideHelp.getInstance().setImg(ChatActivity.this,Integer.valueOf(model.getMsg()),iv);
                }
            }

            @Override
            public int getLayoutId(int type) {
               if(type==0){
                   //左边
                   return R.layout.item_chat_message_left;
               }else{
                   //右边
                   return R.layout.item_chat_message_right;
               }
            }
        });

        binding.rvList.setLayoutManager(new LinearLayoutManager(this));
        binding.rvList.setAdapter(chatMessageAdapter);

        mShowAction =  new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 1.0f, Animation.RELATIVE_TO_SELF, 0.0f);
        mShowAction.setDuration(500);//动画持续的时间为1.5s
        //如果不添加setFillEnabled和setFillAfter则动画执行结束后会自动回到远点
        mShowAction.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {

            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
        //隐藏从化
        mCloseAction = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 0.0f,
                Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 1.0f);
        mCloseAction.setDuration(500);
        mCloseAction.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                //这个selectTime包含选择框
                binding.llMore.setVisibility(View.GONE);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });


    }

    /**
     * 添加文本消息
     * @param s
     */
    private void addTextMsg(String s,int position){
        ChatMessageEntity messageEntity = new ChatMessageEntity();
        messageEntity.setMsg(s);
        messageEntity.setPosition(position);
        messageEntity.setType(APPConstant.RECEIVE_TEXT_CODE);
        chatMessages.add(messageEntity);
        if(chatMessageAdapter==null){
            init();
        }
        chatMessageAdapter.notifyDataSetChanged();
        binding.rvList.smoothScrollToPosition(chatMessageAdapter.getItemCount()-1);
    }

    /**
     * 添加图片信息
     * @param base64
     * @param position
     */
    private void addImageMsg(String base64, int position) {
        if(TextUtils.isEmpty(base64)){
            return;
        }
        Observable.create(new ObservableOnSubscribe<String>() {
            @Override
            public void subscribe(@NonNull ObservableEmitter<String> emitter) throws Throwable {
                String path = ImageUtil.base64ToFile(base64, FileUtil.createImgPath());
                emitter.onNext(path);
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<String>() {
            @Override
            public void accept(String path) throws Throwable {
                //
                if(!TextUtils.isEmpty(path)){

                    ChatMessageEntity m = new ChatMessageEntity();
                    m.setMsg(path);
                    m.setType(APPConstant.RECEIVE_IMG_CODE);
                    m.setPosition(1);
                    chatMessages.add(m);

                    //显示
                    ChatMessageEntity messageEntity = new ChatMessageEntity();
                    messageEntity.setMsg(path);
                    messageEntity.setType(APPConstant.RECEIVE_IMG_CODE);
                    messageEntity.setPosition(position);
                    chatMessages.add(messageEntity);

                    if(chatMessageAdapter==null){
                        init();
                    }
                    chatMessageAdapter.notifyDataSetChanged();
                    binding.rvList.smoothScrollToPosition(chatMessageAdapter.getItemCount()-1);
                }
            }
        });
    }

    /**
     * 添加文件信息
     * @param
     */
    private void addFileMsg(String fileName, int position) {
        if(TextUtils.isEmpty(fileName)){
            return;
        }
        int i = fileName.lastIndexOf(".");
        String end = "error";
        if(i>0){
            end = fileName.substring(i+1);
        }
        Logutils.e("后缀"+end);
        end = end.toLowerCase();
        ChatMessageEntity messageEntity = new ChatMessageEntity();
        switch (end){
            case "jpg":
            case "png":
            case "jpeg":
            case "gif":{
                messageEntity.setMsg(R.drawable.chat_image_icon+"");
                break;
            }
            case "apk":{
                messageEntity.setMsg(R.drawable.chat_android_icon+"");
                break;
            }
            default:{
                messageEntity.setMsg(R.drawable.chat_file_icon+"");
            }
        }
        messageEntity.setPosition(position);
        messageEntity.setType(APPConstant.RECEIVE_FILE_CODE);
        chatMessages.add(messageEntity);
        if(chatMessageAdapter==null){
            init();
        }
        chatMessageAdapter.notifyDataSetChanged();
        binding.rvList.smoothScrollToPosition(chatMessageAdapter.getItemCount()-1);
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.send_btn:{
                sendText();
                break;
            }
            case R.id.iv_more:{
                if (View.GONE == binding.llMore.getVisibility()) {
                    binding.llMore.setVisibility(View.VISIBLE);//selectTime背景色是暗的，所以看起来像是背景变暗
                    binding.llMore.startAnimation(mShowAction);//为选择框设置动画
                }else{
                    binding.llMore.startAnimation(mCloseAction);//为选择框设置动画
                }
                break;
            }
            case R.id.iv_chat_camera:{
                CameraUtil.getInstance().openCamera(this);
                break;
            }
            case R.id.iv_chat_images:{
               //打开图库
                PictureSelector
                        .create(ChatActivity.this, PictureSelector.SELECT_REQUEST_CODE)
                        .selectPicture(true);
                break;
            }
            case R.id.iv_chat_file:{
                FilePickerManager.INSTANCE.from(this)
                        .maxSelectable(1)
                .forResult(FilePickerManager.REQUEST_CODE);

                break;
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == CameraUtil.CAMERA_REQUEST_CODE) {
            if (resultCode == RESULT_OK) {
                String imagePath = CameraUtil.getInstance().getImagePath();
                EventBus.getDefault().post(new ChatMessageEvent(APPConstant.SEND_IMG_CODE,"",imagePath));
            }else{
                Toast.makeText(this,"取消",Toast.LENGTH_LONG).show();
            }
        }else if (requestCode == PictureSelector.SELECT_REQUEST_CODE) {
            Logutils.e("当前-->66");
                if (data != null) {
                    PictureBean pictureBean = data.getParcelableExtra(PictureSelector.PICTURE_RESULT);
                    String path = "";
                    if (pictureBean.isCut()) {
                        path = pictureBean.getPath();
                    } else {
                        path = CameraUtil.getInstance().getFilePathFromUri(AppHelp.getInstance().getContext(),pictureBean.getUri());
                    }
                    if(!TextUtils.isEmpty(path)){
                        EventBus.getDefault().post(new ChatMessageEvent(APPConstant.SEND_IMG_CODE,"",path));
                    }

                    addFileMsg(path,1);
                    //使用 Glide 加载图片
                /*Glide.with(this)
                        .load(pictureBean.isCut() ? pictureBean.getPath() : pictureBean.getUri())
                        .apply(RequestOptions.centerCropTransform()).into(mIvImage);*/
                }
        }else if(requestCode==FilePickerManager.REQUEST_CODE){
            if (resultCode == Activity.RESULT_OK) {
                List<String> list = FilePickerManager.INSTANCE.obtainData();
                if(list!=null&&list.size()>0){
                    System.out.println(list);
                    EventBus.getDefault().post(new ChatMessageEvent(APPConstant.SEND_FILE_CODE,"",list.get(0)));
                    addFileMsg(list.get(0),1);
                }
            }else{
                Toast.makeText(this, "没有选择任何东西~", Toast.LENGTH_SHORT).show();
            }

        }
    }

    /**
     * 发送消息
     */
    private void sendText(){
        //发送数据到服务端
        Observable.create(new ObservableOnSubscribe<String>() {
            @Override
            public void subscribe(@NonNull ObservableEmitter<String> emitter) throws Throwable {
                String str = binding.etMsg.getText().toString();
                //发送数据
                EventBus.getDefault().post(new ChatMessageEvent(APPConstant.SEND_TEXT_CODE,"",str));
                emitter.onNext(str);
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<String>() {
                    @Override
                    public void accept(String s) throws Exception {
                        Logutils.i("发送："+s);
                        addTextMsg(s,1);
                        binding.etMsg.setText("");
                    }
                });
    }

}
